/**
 * Created by admin on 2016/12/13.
 */
'use strict'

let mor = require("../libs/mongo/mongoHelper");
let querystring = require('querystring');
let dbr = require("../libs/mysql/mysqlHelper");
let jv = require("../libs/sys/myHelper").jv;
let http = require('request-promise');

app.use(app.routes.get('/wuye/order/list', async ctx => {
  ctx.render("wuye/order_list");
}));

app.use(app.routes.get('/wuye/order/detail', async ctx => {
  ctx.render("wuye/order_detail");
}));

app.use(app.routes.get('/wuye/message/list', async ctx => {
  ctx.render("message/list");
}));

app.use(app.routes.get('/wuye/message/detail', async ctx => {
  ctx.render("message/detail");
}));

app.use(app.routes.get('/wuye/fee/list', async ctx => {
  ctx.render("fee/list");
}));

app.use(app.routes.get('/wuye/fee/detail', async ctx => {
  ctx.render("fee/detail");
}));

app.use(app.routes.get('/wuye/user/info', async ctx => {
  ctx.render("wuye/user_info");
}));

app.use(app.routes.post('/wuye/user/info', async ctx => {
  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }

  let result = await dbr.findOne(`select u.id,u.name,u.mobile,u.email ,o.name corpName
from sys_user u
join sys_office o on ( u.company_id = o.id)
where u.id=:userId`, {userId: userId});
  if (!result) {
    return ctx.msg = "找不到物业人员信息";
  }
  ctx.body = result;
}));

app.use(app.routes.post('/wuye/user/save', async ctx => {
  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }

  let result = await dbr.update("sys_user", jv.retain(ctx.req.json, "name", "mobile", "email"), {id: userId});
  if (!result || !result.affectedRows) {
    return ctx.msg = "更新失败";
  }
}));


//获取其它物业人员
app.use(app.routes.post('/wuye/getOther', async ctx => {
  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }


  let results = await dbr.find(`select ou.id,ou.name
from sys_user ou
where  exists ( select 1 from sys_user mu where mu.id = :userId and mu.company_id = ou.company_id )
and ou.del_flag=0 and ou.login_flag=1`,
    {userId: userId});

  ctx.body = results;
}));


//获取阿姨
app.use(app.routes.post('/wuye/getAyis', async ctx => {
  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }


  let results = await dbr.find(`select ou.id,ou.name
from thwy_worker ou
join thwy_user_worker uw on ( ou.id = uw.worker_id )
where  uw.user_id = :userId and ou.del_flag=0 and ou.if_receive_new_task=1 and ou.is_enable=1 `,
    {userId: userId});

  ctx.body = results || [];
}));


app.use(app.routes.post('/wuye/order/list', async ctx => {
  let params = querystring.parse(ctx.req._parsedUrl.query);

  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }


  let skip = ctx.req.json.skip;
  let take = ctx.req.json.take;

  let results = await dbr.find(`select o.id, f.name fuwuName , o.\`status\` , o.total_amount total , o.contact_name contactor, o.mobile , o.detailed_address address ,
usr.name wuyeName , o.create_date
from thwy_order o
join thwy_fuwu f on ( o.fuwu_id = f.id ) 
join  thwy_order_user ou  on ( o.id = ou.order_id and ou.status != 'transferred' )
join sys_user usr on ( ou.receiver = usr.id)
where  ( ou.receiver = :userId and ou.status != 'completed' ) or ( ou.distributor = :userId and ou.\`status\` = 'waiting' )
order by o.create_date desc
limit :skip,:take`,
    {userId: userId, skip: skip, take: take});

  if (!results || !results.length) {
    ctx.body = [];
    return;
  }

  results.forEach(it => {
    it.items = [];
  });

  let items = await dbr.find(`select id, name,quantity,price_payable fee,order_id orderId
from thwy_order_item
where order_id in (${results.map(it => {
    return '"' + it.id + '"';
  }).join(",")}) and del_flag =0 `);
  if (items && items.length) {
    items.forEach(it => {
      results.filter(order => {
        return order.id == it.orderId
      })[0].items.push(it);
    });
  }

  ctx.body = results;
}));

//转到其它物业
app.use(app.routes.post('/wuye/toWuye', async ctx => {
  let params = querystring.parse(ctx.req._parsedUrl.query);

  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }

  let recvId = ctx.req.json.userId;
  let orderId = ctx.req.json.orderId;

  if (!orderId) {
    ctx.msg = "找不到订单Id";
    return;
  }
  if (!recvId) {
    ctx.msg = "找不到接收人";
    return;
  }

  let result = await dbr.findOne("select id,receiver from thwy_order_user where order_id = :orderId and (status != 'transferred') and del_flag = 0 ", {orderId: orderId});


  if (!result) {
    ctx.msg = "找不到订单信息";
    return;
  }

  if (result.status == 'received' && result.receiver != userId) {
    ctx.msg = "非法操作";
    return;
  }
  else if (result.status == 'waiting' && (result.receiver != userId || result.distributor != userId)) {
    ctx.msg = "非法操作";
    return;
  }

  result = await dbr.update("thwy_order_user", {status: "transferred"}, {order_id: orderId});
  if (!result.affectedRows) {
    ctx.msg = "更新状态失败";
    return;
  }

  //插入
  result = await dbr.insert("thwy_order_user", {
    id: jv.randomCode(),
    order_id: orderId,
    receiver: recvId,
    distributor: userId,
    status: "waiting",
    create_by: userId,
    create_date: new Date(),
    del_flag: 0
  });
  if (!result.affectedRows) {
    //回滚？
    result = await dbr.update("thwy_order_user", {status: "waiting"}, {id: orderId});

    ctx.msg = "转出失败";
    return;
  }
}));


//转给阿姨
app.use(app.routes.post('/wuye/toAyi', async ctx => {

  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }

  let workerId = ctx.req.json.workerId;
  let orderId = ctx.req.json.orderId;

  if (!orderId) {
    ctx.msg = "找不到订单Id";
    return;
  }
  if (!workerId) {
    ctx.msg = "找不到接收人";
    return;
  }


  let result = await dbr.update("thwy_order_worker", {
    worker_id: workerId,
    update_date: new Date()
  }, {order_id: orderId});

  if (result.affectedRows) {
    return;
  }

  //插入
  result = await dbr.insert("thwy_order_user", {
    order_id: orderId,
    distributor: userId,
    worker_id: workerId,
    create_date: new Date(),
    del_flag: 0
  });
  if (!result.affectedRows) {
    ctx.msg = "转出失败";
    return;
  }

}));


app.use(app.routes.post('/wuye/order/detail', async ctx => {

  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }

  let orderId = ctx.req.json.orderId;

  if (!orderId) {
    ctx.msg = "找不到订单Id";
    return;
  }

  let results = await dbr.findOne(`select o.id, o.status , o.amount_payable total ,
o.contact_name contactor,o.mobile , o.detailed_address address , o.is_upload_video, o.video_link ,o.create_date,
f.name fuwuName 
from thwy_order o
join thwy_fuwu f on (o.fuwu_id = f.id)
left join thwy_order_user ou on (o.id = ou.order_id and ( ou.status != 'transferred' ))
where o.id=:orderId  and (ou.receiver=:userId or ou.distributor=:userId)`,
    {orderId: orderId, userId: userId});

  if (!results) {
    return;
  }

  let wuyeInfo = await dbr.findOne(`select usr.name wuyeName , ou.status from  thwy_order_user ou 
join sys_user usr on ( ou.receiver = usr.id )
where ou.order_id = :orderId and ( ou.status != 'transferred' ) `, {orderId: orderId});


  results.wuyeName = wuyeInfo && wuyeInfo.wuyeName || "";
  results.ayiName = "";

  if (wuyeInfo.status == 'received') {
    let ayiName = await dbr.findOne(`select fw.username ayiName from thwy_order_worker ow 
left join thwy_worker fw on ( ow.worker_id = fw.id )
where ow.order_id = :orderId`, {orderId: orderId});

    if (ayiName) {
      results.ayiName = ayiName;
    }
  }


  let items = await dbr.find(`select id, name,quantity,price_payable fee,order_id orderId
from thwy_order_item 
where order_id  = :orderId `, {orderId: orderId});

  results.items = items;

  ctx.body = results;
}));


app.use(app.routes.post('/wuye/order/setCancel', async ctx => {
  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }
  let amount = ctx.req.json.amount;
  let orderId = ctx.req.json.orderId;
  let user = ctx.session.user;
  if (!orderId) {
    ctx.msg = "找不到订单号";
    return;
  }

  let order = await dbr.findOne("select * from thwy_order where id=:orderId", {orderId: orderId});
  if (!order) {
    return ctx.msg = "找不到订单信息";
  }

  //必须接收者是我。
  let result = await dbr.update("thwy_order", {status: "cancelled"}, {id: orderId});
  if (!result || !result.affectedRows) {
    return ctx.msg = "设置服务状态失败";
  }


  result = await dbr.insert("thwy_order_log", {
    id: jv.randomCode(),
    order_id: orderId,
    content: `${user.name} 把订单取消了。`,
    status: order.status, operator: userId, create_date: new Date(),
  });
}));

app.use(app.routes.post('/wuye/order/setAmount', async ctx => {
  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }
  let amount = ctx.req.json.amount;
  let orderId = ctx.req.json.orderId;
  let user = ctx.session.user;
  if (!orderId) {
    ctx.msg = "找不到订单号";
    return;
  }
  let order = await dbr.findOne("select * from thwy_order where id=:orderId", {orderId: orderId});
  if (!order) {
    return ctx.msg = "找不到订单信息";
  }

  let result = await dbr.update("thwy_order", {amount_payable: amount}, {id: orderId});
  if (!result || !result.affectedRows) {
    return ctx.msg = "修改失败";
  }

  result = await dbr.insert("thwy_order_log", {
    id: jv.randomCode(),
    order_id: orderId,
    content: `${user.name} 修改了订单金额，从${order.amount_payable} 修改为 ${amount}`,
    status: order.status, operator: userId, create_date: new Date(),
  });
}));

//设置 确认 状态。
app.use(app.routes.post('/wuye/order/setConfirm', async ctx => {
  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }

  let orderId = ctx.req.json.orderId;
  let user = ctx.session.user;
  if (!orderId) {
    ctx.msg = "找不到订单号";
    return;
  }

  let order = await dbr.findOne("select * from thwy_order where id=:orderId", {orderId: orderId});
  if (!order) {
    return ctx.msg = "找不到订单信息";
  }
  if (order.status != "paid" && !order.status != "waitPay") {
    return ctx.msg = "不能再设置为 已确认";
  }

  //必须接收者是我。
  let result = await dbr.update("thwy_order_user", {status: "received"}, {order_id: orderId, status: "waiting"});
  if (!result || !result.affectedRows) {
    return ctx.msg = "设置服务状态失败";
  }

  if (order.status == "waitPay") {
    result = await dbr.update("thwy_order", {status: "confirmed"}, {id: orderId});
    ctx.body = {status: "confirmed"};
  }
  else {
    result = await dbr.update("thwy_order", {status: "confirmedPaid"}, {id: orderId});
    ctx.body = {status: "confirmedPaid"};
  }
  if (!result || !result.affectedRows) {
    return ctx.msg = "设置服务状态失败";
  }

  result = await dbr.insert("thwy_order_log", {
    id: jv.randomCode(),
    order_id: orderId,
    content: `${user.name} 把订单服务状态从${order.status}设置为 已确认。`,
    status: order.status, operator: userId, create_date: new Date(),
  });
}));

app.use(app.routes.post('/wuye/order/setDone', async ctx => {
  let userId = ctx.needLogin();
  if (!userId) {
    return;
  }

  let orderId = ctx.req.json.orderId;
  let user = ctx.session.user;
  if (!orderId) {
    ctx.msg = "找不到订单号";
    return;
  }
  let order = await dbr.findOne("select * from thwy_order where id=:orderId", {orderId: orderId});
  if (!order) {
    return ctx.msg = "找不到订单信息";
  }

  if (order.status == "completed") {
    return ctx.msg = "订单已完成，不能再设置为完成";
  }
  if (order.status == "closed") {
    return ctx.msg = "订单已关闭，不能再设置为完成";
  }
  if (order.status == "cancelled") {
    return ctx.msg = "订单已取消，不能再设置为完成";
  }

  let result = await dbr.update("thwy_order", {status: "completed"}, {id: orderId});
  if (!result || !result.affectedRows) {
    return ctx.msg = "设置服务状态失败";
  }

  result = await dbr.insert("thwy_order_log", {
    id: jv.randomCode(),
    order_id: orderId,
    content: `${user.name} 把订单服务状态从${order.status}设置为完成。`,
    status: order.status, operator: userId, create_date: new Date(),
  });

  //如果记录日志失败，怎么办？
}));
